import React, {useRef, useState} from "react";
import ProForm, {FormInstance, ProFormText} from "@ant-design/pro-form"
import {Button, Form, Input, ModalProps} from "antd";
import {PlusOutlined} from "@ant-design/icons";
import {ModalPermission} from "@/components/Permission";
import departmentService from "@/services/department";
import {DepartmentDTO, DepartmentQueryDTO, DepartmentVO} from "@/types/department";
import {OptionType} from "@/types/common";
import {arrayToTree} from "@/utils/utils";
import CustomTreeSelect from "@/components/CustomTreeSelect";

interface DepartmentFormProps{
  entity?:DepartmentVO;
  options?:OptionType[];
  onFinish?: (formData:any) => Promise<any | void>;
  /** @name 用于触发抽屉打开的 dom */
  trigger?: JSX.Element;
  /** @name 获取真正的可以获得值的 from */
  formRef?: React.MutableRefObject<(FormInstance & {
    getFieldsFormatValue?: () => any;
  }) | undefined>;
  onReset:()=>void;
  functionKey?:string;
  /** @name 打开关闭的事件 */
  onVisibleChange?: (visible: boolean) => void;
  /** @name 受控的打开关闭 */
  visible?: ModalProps['visible'];
}

const create= async (params:DepartmentDTO): Promise<DepartmentVO> => {
  const response=await departmentService.create(params);
  const {data}=response;
  return new Promise((resolve, reject) => {
    resolve(data);
  })
}

const modify= async (params:DepartmentDTO): Promise<DepartmentVO> => {
  const response=await departmentService.modify(params);
  const {data}=response;
  return new Promise((resolve, reject) => {
    resolve(data);
  })
}

const queryList= async (dto:DepartmentQueryDTO): Promise<OptionType[]> => {
  const response=await departmentService.queryList(dto);
  const {data}=response;
  return arrayToTree(data);
}

const DepartmentForm:React.FC<DepartmentFormProps> = (props) =>{

  const formRef = useRef<FormInstance>();

  const onFinish=async (values:any) => {
    return new Promise<boolean|void>((resolve, reject)=>{
      if(props.onFinish){
        props.onFinish(values)
          .then((data)=>{
            if(data){
              resolve(true);
              props.onReset();
              formRef.current?.resetFields();
            }else{
              reject();
            }
          });
      }
    })
  }

  return (
    <ModalPermission
      formRef={formRef}
      functionKey={props.functionKey}
      visible={props.visible}
      onVisibleChange={props.onVisibleChange}
      trigger={props.trigger}
      onFinish={onFinish}
      initialValues={{
        id:props.entity?.id,
        name:props.entity?.name,
        parentId:props.entity?.parentId,
        organizationId:props.entity?.organizationId,
      }}
    >
      <ProForm.Group>
        <Form.Item name="id">
          <Input type={'hidden'} />
        </Form.Item>
        <ProFormText
          width="md"
          name="name"
          label="部门名称"
          rules={[
            {required:true,message:'请输入部门名称'}
          ]}
          placeholder="请输入部门名称"
        />
        <Form.Item
          className={'pro-field-md'}
          name={'parentId'}
          label="上级部门"
        >
          <CustomTreeSelect list={props.options} multiple={false}/>
        </Form.Item>
        <Form.Item name="organizationId">
          <Input type={'hidden'} />
        </Form.Item>
      </ProForm.Group>
    </ModalPermission>
  )
}

export const DepartmentCreateForm:React.FC<DepartmentFormProps> = (props) =>{
  const formRef = useRef<FormInstance>();

  const [options,setOptions] = useState<OptionType[]>([]);

  const onClick=()=>{
    queryList({
      organizationId:props.entity?.organizationId,
    })
      .then(data=>{
        setOptions(data);
    })
    formRef.current?.setFieldsValue({
      id:props.entity?.id,
      name:props.entity?.name,
      parentId:props.entity?.parentId,
      organizationId:props.entity?.organizationId,
    })
  }

  return (
    <DepartmentForm
      {...props}
      options={options}
      formRef={formRef}
      onFinish={create}
      trigger={
        <Button type="primary" onClick={onClick}>
          <PlusOutlined />
          新建部门
        </Button>
      }
    />
  )
}

export const DepartmentModifyForm:React.FC<DepartmentFormProps> = (props) =>{
  const formRef = useRef<FormInstance>();

  const [options,setOptions] = useState<OptionType[]>([]);

  const onVisibleChange=(visible: boolean)=>{
    if(visible){
      queryList({
        organizationId:props.entity?.organizationId,
      })
        .then(data=>{
          setOptions(data);
        })
      formRef.current?.setFieldsValue({
        id:props.entity?.id,
        name:props.entity?.name,
        parentId:props.entity?.parentId,
        organizationId:props.entity?.organizationId,
      })
    }
    if(props.onVisibleChange && !visible){
      props.onVisibleChange(visible);
    }
  }

  return (
    <DepartmentForm
      {...props}
      options={options}
      formRef={formRef}
      onFinish={modify}
      onVisibleChange={onVisibleChange}
    />
  )
}

